import io

import pandas as pd
from aiogram import Bot, types
from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.bot.services.tg_helpers import answer_msg_with_autodelete
from src.core.exceptions.product import (
    ProductEmailAlreadyExist,
    ProductLoginAlreadyExist,
)
from src.core.utils.files import get_file_extension
from src.database.services.category import CategoryService
from src.database.services.product import ProductService


async def set_category_id(
    _,
    __,
    manager: DialogManager,
    category_id: str,
):
    manager.dialog_data["category_id"] = int(category_id)
    await manager.next()


async def process_products_file(message: types.Message, _, manager: DialogManager):
    """Импортируем товары из эксель файла"""

    bot: Bot = manager.middleware_data.get("bot")
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    product_service: ProductService = manager.middleware_data.get("product_service")

    category_id: int = manager.dialog_data.get("category_id")
    extension = get_file_extension(message.document.file_name)

    if extension != "xlsx":
        await answer_msg_with_autodelete(message, locale.get("wrong-file-extension"))
        return

    file = await bot.get_file(message.document.file_id)

    destination_path = io.BytesIO()
    msg = await message.answer("Обрабатываю файл")
    await bot.download_file(file.file_path, destination_path)
    excel_content = pd.read_excel(destination_path)
    excel_content.replace({pd.NA: None}, inplace=True)
    records = excel_content.to_dict(orient="records")

    created_count = 0
    for i, line in enumerate(records, start=1):
        if not line.get("first_name"):
            await message.answer(f"Не заполнено имя в строке {i}")
            continue
        elif not line.get("last_name"):
            await message.answer(f"Не заполнена фамилия в строке {i}")
            continue
        elif not line.get("login"):
            await message.answer(f"Не заполнен логин в строке {i}")
            continue
        elif not line.get("password"):
            await message.answer(f"Не заполнен пароль в строке {i}")
            continue
        elif not line.get("email"):
            await message.answer(f"Не заполнен email в строке {i}")
            continue

        try:
            await product_service.create_product(
                line.get("first_name"),
                line.get("last_name"),
                line.get("year"),
                line.get("month"),
                line.get("day"),
                line.get("gender"),
                line.get("house_num"),
                line.get("street_name"),
                line.get("post_code"),
                line.get("login"),
                line.get("password"),
                line.get("email"),
                category_id,
                line.get("email_password"),
                line.get("cpf"),
                line.get("docs"),
            )
        except ProductEmailAlreadyExist:
            await message.answer(f"Товар с email {line.get('email')} уже существует")
            continue
        except ProductLoginAlreadyExist:
            await message.answer(f"Товар с логином {line.get('login')} уже существует")
            continue

        created_count += 1

    await msg.delete()
    await message.answer(f"Создано товаров: {created_count} из {len(records)}")

    await manager.done()
